package com.gyms.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.classic.okhttp.beans.HVVenueBean;
import com.classic.okhttp.beans.HVVenueLabelBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.activity.CodeLoginActivity;
import com.gyms.base.BaseActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.DataCenter;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import constant.PicSplit;
import glide.ImageLoaderUtils;
import myInterface.OnItemClickLitener;
import utils.DecimalUtils;
import utils.ScreenUtils;
import utils.SizeUtils;
import utils.StringUtils;
import weight.CommonEmptyView;

/**
 * yjl on 2016/11/4 13:17
 * 一个适配器搞定侧滑删除
 */
public class MyGymAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<HVVenueBean> mHVVenueBeans;
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private View view;
    // 屏幕宽度,由于我们用的是HorizontalScrollView,所以按钮选项应该在屏幕外
    private int mScreentWidth;
    private boolean isClose = true;
    private OnItemClickLitener mOnItemClickLitener;//Item的点击监听
    private Dialog loadingView;
    private int clickposition;//点击位置
    private CommonEmptyView searchEmpty;
    private View contentView;

    private int mHeadRes;//头部资源

    public void setHeadRes(int mHeadRes){
        this.mHeadRes=mHeadRes;
    }
    private int getHeadCount(){
        return mHeadRes==0?0:1;
    }

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    public MyGymAdapter(Context mContext, int screentWidth, List<HVVenueBean> mHVVenueBeans, Dialog loadingViews,CommonEmptyView searchEmpty,View contentView) {
        this.mContext = mContext;
        loadingView = loadingViews;
        this.mScreentWidth = screentWidth;
        this.searchEmpty=searchEmpty;
        this.contentView=contentView;
        this.mHVVenueBeans = mHVVenueBeans;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    public void setData(List<HVVenueBean> venuePic) {
        this.mHVVenueBeans.addAll(venuePic);
        notifyDataSetChanged();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder mViewHolder=null;
        switch (viewType){
            case Constants.S_TYPE_HEAD://head
                View mHeadView=LayoutInflater.from(mContext).inflate(mHeadRes,parent,false);
                mViewHolder=new HeadViewHolder(mHeadView);
                break;

            case Constants.S_TYPE_NOM://正常的vIew
                 View view = mLayoutInflater.inflate(R.layout.my_gym_item, parent, false);
                 mViewHolder = new MyGymAdapter.GymViewHolder(view);
                // 设置内容view的大小为屏幕宽度,这样按钮就正好被挤出屏幕外
                ViewGroup.LayoutParams lp = ((GymViewHolder)mViewHolder).content.getLayoutParams();
                lp.width = mScreentWidth;
                break;
        }

        return mViewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder mViewHolder, final int position) {
        int mViewType=getItemViewType(position);
        if(StringUtils.isNull(mHVVenueBeans)){
            return;
        }
        switch (mViewType){
            case Constants.S_TYPE_HEAD:

                break;


            case Constants.S_TYPE_NOM:
                HVVenueBean mHVVenueBean = mHVVenueBeans.get(position-getHeadCount());
                 GymViewHolder mGymViewHolder= (GymViewHolder) mViewHolder;
                if (!StringUtils.isNull(mHVVenueBean)) {
                    initData(mGymViewHolder, mHVVenueBean);
                }

                mViewHolder.itemView.setTag(R.id.rb_home,position);
                mViewHolder.itemView.setTag(mViewHolder);
                // 设置监听事件
                mViewHolder.itemView.setOnTouchListener(touchListener);
                // 这里防止删除一条item后,ListView处于操作状态,直接还原
                if (mGymViewHolder.hSView.getScrollX() != 0) {
                    mGymViewHolder.hSView.scrollTo(0, 0);
                }
                mGymViewHolder.canncleBtn.setTag(position);
                mGymViewHolder.canncleBtn.setTag(R.id.textView, mViewHolder);
                mGymViewHolder.canncleBtn.setOnClickListener(onClickListener);
                break;
        }

    }

    @Override
    public int getItemCount() {
        int mDataSize=null==mHVVenueBeans?0:mHVVenueBeans.size()+getHeadCount();
        return mDataSize;
    }

    @Override
    public int getItemViewType(int position) {
        if (position<getHeadCount()) return Constants.S_TYPE_HEAD;

        return Constants.S_TYPE_NOM;
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            GymViewHolder viewHolder1 = (GymViewHolder) v.getTag(R.id.textView);
            clickposition = (int) v.getTag();
            viewHolder1.hSView.smoothScrollTo(0, 0);
            //请求取消收藏
            sartActivityIsLogin(mHVVenueBeans.get(clickposition-getHeadCount()));
        }
    };


    View.OnTouchListener touchListener = new View.OnTouchListener() {

        private int y;
        private int x;
        //计算点击事件
        private float y2;
        private float x2;
        private float x1;
        private float y1;
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (view != null) {
                        GymViewHolder viewHolder1 = (GymViewHolder) view.getTag();
                        viewHolder1.hSView.smoothScrollTo(0, 0);
                    }
                    x = (int) event.getX();
                    y = (int) event.getY();

                    x1 =  event.getRawX();//得到相对应屏幕左上角的坐标
                    y1 =  event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int x3 = (int) event.getX();
                    int y3 = (int) event.getY();
                    int dY = Math.abs(y - y3);
                    int dx = Math.abs(x - x3);
                    if (dx > dY && dx > 20) {
//                    		((ViewGroup) v).requestDisallowInterceptTouchEvent(true);
                    }

                    break;
                case MotionEvent.ACTION_UP:
                    // 获得ViewHolder
                    GymViewHolder viewHolder = (GymViewHolder) v.getTag();
                    int position = (int) v.getTag(R.id.rb_home);
                    view = v;
                    // 获得HorizontalScrollView滑动的水平方向值.
                    int scrollX = viewHolder.hSView.getScrollX();
                    // 获得操作区域的长度
                    int actionW = viewHolder.action.getWidth();

                    // 注意使用smoothScrollTo,这样效果看起来比较圆滑,不生硬
                    // 如果水平方向的移动值<操作区域的长度的一半,就复原
                    if (isClose) {
                        if (scrollX < (actionW / 5)) {
                            isClose = true;
                            viewHolder.hSView.smoothScrollTo(0, 0);
                        } else// 否则的话显示操作区域
                        {
                            isClose = false;
                            viewHolder.hSView.smoothScrollTo(actionW, 0);
                        }

                    } else {

                        if (scrollX < (actionW * 4.0 / 5.0)) {
                            isClose = true;
                            viewHolder.hSView.smoothScrollTo(0, 0);
                        } else// 否则的话显示操作区域
                        {
                            isClose = false;
                            viewHolder.hSView.smoothScrollTo(actionW, 0);
                        }
                    }

                    x2 = event.getRawX();
                    y2 = event.getRawY();
//                    Log.i("i", x1 + ",,," + y1 +",,,"+x2+",,,"+y2);
                    double distance = Math.sqrt(Math.abs(x1-x2)*Math.abs(x1-x2)+Math.abs(y1-y2)*Math.abs(y1-y2));//两点之间的距离
//                    Log.i("i", "x1 - x2>>>>>>"+ distance);
                    if (distance < 15) { // 距离较小，当作click事件来处理
                        if (mOnItemClickLitener != null) {
                            viewHolder.hSView.smoothScrollTo(0, 0);
                            mOnItemClickLitener.onItemClick(v, position-getHeadCount());
                        }
                        return false;
                    } else {
                        return true ;
                    }
            }
            return false;
        }
    };

    private void initData(GymViewHolder mViewHolder, HVVenueBean mHVVenueBean) {
        boolean isCollection=mHVVenueBean.getIsCollection();//收藏
        boolean isRecommend=mHVVenueBean.getIsRecommend();//推荐
        boolean isVenueOnline=mHVVenueBean.getVenueState();//场馆是否上架
        if(!isCollection&&!isRecommend){
            mViewHolder.mIvCollect.setVisibility(View.GONE);
        }else{
            mViewHolder.mIvCollect.setVisibility(View.VISIBLE);
        }
        if (isRecommend) {
            mViewHolder.mIvCollect.setImageResource(R.mipmap.icon_best);
        }
        if (isCollection) {//收藏大于推荐
            mViewHolder.mIvCollect.setImageResource(R.mipmap.icon_save_subscript);
        }

        mViewHolder.mTvGymName.setText(StringUtils.CS(mHVVenueBean.getVenueName()));
        mViewHolder.mTvGymDes.setText(StringUtils.CS(mHVVenueBean.getShortAddress()));
        double price = 0.0;
       /* if (!StringUtils.isNull(mHVVenueBean.getMinPrice())) {
            price = mHVVenueBean.getMinPrice();
        }*/
        /*场馆列表中，非线上预订场馆，没有价格按钮*/
        if (0.0 == price) {
            mViewHolder.mTvPrice.setVisibility(View.GONE);
        } else {
//            mViewHolder.mTvPrice.setText(DecimalUtils.doubleToIntOrD(price) + "元");
            mViewHolder.mTvPrice.setText(DecimalUtils.setPriceStyle(mContext,price,R.dimen.price_text_size_14,R.dimen.price_text_size_12,true));
        }
        //如果已下架就 显示出已下架
        if(isVenueOnline){
            mViewHolder.mTvGymLostView.setVisibility(View.GONE);//已上架就隐藏
        }else{
            mViewHolder.mTvGymLostView.setVisibility(View.VISIBLE);//已下架就显示
            ViewGroup.LayoutParams lpGymLostView = mViewHolder.mTvGymLostView.getLayoutParams();
            lpGymLostView.height= ScreenUtils.getViewHight(mViewHolder.content);//计算高度
        }
        mViewHolder.mIvCollect.setVisibility(mHVVenueBean.getIsCollection() ? View.VISIBLE : View.GONE);
        ImageLoaderUtils.display(mContext, mViewHolder.mIvGym, mHVVenueBean.getVenueUrl());
        if (!StringUtils.isNull(mHVVenueBean.getDistance())) {
//            double dis = mHVVenueBean.getDistance() / 1000;
//            if (dis < 100) {
//                mViewHolder.mTvGymDis.setText("<100m");
//            } else {
//                mViewHolder.mTvGymDis.setText(dis + "m");
//            }

            double dis = mHVVenueBean.getDistance() / 1000;
            showDis(mViewHolder, dis);
        }

        if(!StringUtils.isNull(mHVVenueBean.getVenueDiscount())){
            mViewHolder.mLlGymDiscount.setVisibility(View.GONE);
            String discountUrl=mHVVenueBean.getVenueDiscount().get(0).getDiscountIcon();//优惠图片
            String mDiscountContent=mHVVenueBean.getVenueDiscount().get(0).getDiscountContent();//优惠文本
            if(!StringUtils.isNull(discountUrl)){//优惠的图片为null隐藏
                mViewHolder.mLlGymDiscount.setVisibility(View.VISIBLE);
                mViewHolder.mTvDiscount.setVisibility(View.VISIBLE);
                ImageLoaderUtils.display(mContext, mViewHolder.mTvDiscount, PicSplit.urlAdd(discountUrl,PicSplit.TYPE_TAB));
            }else {
                mViewHolder.mTvDiscount.setVisibility(View.GONE);

            }
            mViewHolder.mTvdistanceText.setText(StringUtils.CS(mDiscountContent));

        }else{//为空就隐藏
            mViewHolder.mLlGymDiscount.setVisibility(View.GONE);
//            mViewHolder.mTvDiscount.setVisibility(View.GONE);
        }

        List<HVVenueLabelBean> mHVVenueLabelBeans = mHVVenueBean.getVenueLabel();
        if(!StringUtils.isNull(mHVVenueLabelBeans)){//标签为null
            mViewHolder.mLLTabAdd.setVisibility(View.VISIBLE);
            mViewHolder.mLLTabAdd.removeAllViews();
            for (int pos = 0; pos < mHVVenueLabelBeans.size(); pos++) {
                //最多显示三个
                if (pos == 3) {//如果第三个就停止循环
                    break;
                }
                ImageView iv = new ImageView(mContext);
                LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, SizeUtils.dp2px(mContext, 15));

                if (pos != 0) {
                    ll.setMargins(SizeUtils.dp2px(mContext, 5), 0, 0, 0);
                }
                iv.setLayoutParams(ll);
                Glide.with(mContext).load(mHVVenueLabelBeans.get(pos).getDiscountIcon()).fitCenter().into(iv);
                mViewHolder.mLLTabAdd.addView(iv);
            }
        }else{
            mViewHolder.mLLTabAdd.setVisibility(View.GONE);
        }
    }

    /**
     * 小于1公里的，距离显示“<1km”；大于等于1公里，小于等于50公里的，距离显示“xx.xkm”；大于50公里的，距离显示“>50km”；
     *
     * @param dis 公里
     */
    private void showDis(GymViewHolder mViewHolder,double dis) {
        String disText;
        if (dis < 1) {
            mViewHolder.mTvGymDis.setText("<1km");
        } else if (dis >= 1 && dis <= 50) {
            disText=DecimalUtils.getDistaceText(dis);
            mViewHolder.mTvGymDis.setText(disText + "km");
        } else {
            mViewHolder.mTvGymDis.setText(">50km");
        }
    }

    class GymViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_gym)
        ImageView mIvGym;//场馆图片
        @BindView(R.id.tv_gym_name)
        TextView mTvGymName;//场馆名
        @BindView(R.id.tv_gym_des)
        TextView mTvGymDes;//描述
        @BindView(R.id.tv_gym_dis)
        TextView mTvGymDis;//距离
        @BindView(R.id.ll_tab_add)
        LinearLayout mLLTabAdd; //添加tab的layout
        @BindView(R.id.tv_discount)
        ImageView mTvDiscount;//优惠
        @BindView(R.id.iv_collect)
        ImageView mIvCollect;//是否收藏
        @BindView(R.id.tv_price)
        TextView mTvPrice;
        @BindView(R.id.tv_distance_text)
        TextView mTvdistanceText;//优惠文字
        @BindView(R.id.hsv)
        HorizontalScrollView hSView;
        @BindView(R.id.ll_content)
        View content;
        @BindView(R.id.canncle_button)
        Button canncleBtn;
        @BindView(R.id.ll_action)
        View action;
        @BindView(R.id.tv_lost_view)
        TextView mTvGymLostView;//标识已下架的场馆
        @BindView(R.id.ll_gym_discount)
        LinearLayout mLlGymDiscount;//优惠信息

        GymViewHolder(View view) {
            super(view);
            AutoUtils.autoSize(view);
            ButterKnife.bind(this, view);
        }
    }

    private class HeadViewHolder extends RecyclerView.ViewHolder{

        public HeadViewHolder(View itemView) {
            super(itemView);
        }
    }

    /**
     * 根据具体的网络尺寸加载
     * @param mHVVenueLabelBeans 标签的数据集
     */

   /* private void doShowUrlImg(final List<HVVenueLabelBean> mHVVenueLabelBeans, final int mImgPos) {
        if(mImgPos>=mHVVenueLabelBeans.size()){//当pos超出return
            return;
        }
        final ImageView mIv = new ImageView(mContext);
        final String url=mHVVenueLabelBeans.get(mImgPos).getDiscountIcon();
        Glide.with(mContext)//activty
                .load( mHVVenueLabelBeans.get(mImgPos).getDiscountIcon())
                .asBitmap()
                .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {

                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
                        // Do something with bitmap here.
                        int h= bitmap.getHeight(); //获取bitmap信息，可赋值给外部变量操作，也可在此时行操作。
                        int w= bitmap.getWidth();
                        LinearLayout.LayoutParams ll=new LinearLayout.LayoutParams(w,h);
                        if(mImgPos!=0){//就第一个不margin left 5dp
                            ll.setMargins(SizeUtils.dp2px(mContext,5),0,0,0);
                        }
                        mIv.setLayoutParams(ll);
                        ImageLoaderUtils.display(mContext, mIv, url);
                        images.add(mIv);
                        holder.mLLTabAdd.addView(mIv);
                        mImgPos++;
                        doShowUrlImg(mHVVenueLabelBeans);
                    }
                });

    }*/

    /**
     * 是否登录判断跳转 ,取消收藏
     */
    public void sartActivityIsLogin(HVVenueBean mVVenueInfoBean) {
        if (!DataCenter.getInstance().checkIsLogin()) {
            ToastUtil.showToast(mContext, "请登录后重试");
            ((BaseActivity) mContext).startActivity(CodeLoginActivity.class, false);
        } else {
            if (!StringUtils.isNull(mVVenueInfoBean)) {
                if (loadingView != null)
                    loadingView.show();
                IUserService.cancelMyCollection((Activity) mContext, Enum.EnumCollect.Venue, mVVenueInfoBean.getVenueId(), false, new ObjectCallback<Object>() {
                    @Override
                    public void onSuccess(Object response, String message) {
                        mHVVenueBeans.remove(clickposition-getHeadCount());
                        if(mHVVenueBeans.size()==0){
                            showEmptyView(searchEmpty, 1);
                        }
                        notifyDataSetChanged();
                        ToastUtil.showToast(mContext, message);
                        if (loadingView != null) {
                            loadingView.dismiss();
                        }
                    }

                    @Override
                    public void onErrorT(int code, Object response, String errorMessage) {
                        ToastUtil.showToast(mContext, errorMessage);
                        if (loadingView != null) {
                            loadingView.dismiss();
                        }
                    }

                    @Override
                    public void onHttpErrorCall(int statusCode) {
                        if (loadingView != null) {
                            loadingView.dismiss();
                        }
                    }
                });
            }
        }
    }


    /**
     * 显示空界面或错误界面
     * @param mSearchEmpty
     * @param code  非-100为无内容界面，否则为无网络界面
     */
    protected void showEmptyView(CommonEmptyView mSearchEmpty, int code) {
        if(!StringUtils.isNull(mSearchEmpty)) {
            if (code == Constants.NO_NET) {//无网络的状态
                mSearchEmpty.setImgContent(Constants.TYPE_FAIL);
                mSearchEmpty.setVisibility(View.VISIBLE);
                contentView.setVisibility(View.GONE);
            } else {
                mSearchEmpty.setVisibility(View.VISIBLE);//空页面出现
                contentView.setVisibility(View.GONE);
                mSearchEmpty.setFailText(Constants.SEARCH_FAIL_TEXT);
                mSearchEmpty.setImgContent(Constants.TYPE_NOME);
            }
        }
    }

}
